import { NgZone, OnDestroy, Component, ViewChild, Input, Output, EventEmitter } from '@angular/core';
import { AqmComponent } from 'angular-qq-maps';
declare const qq: any;

@Component({
    selector: 'qq-map',
    templateUrl: './qq-map.component.html',
    styleUrls: ['./qq-map.component.scss']
})
export class QqMapComponent implements OnDestroy {

    @Input() options: any;
    @Output() redirect = new EventEmitter();

    @ViewChild('map') mapComp: AqmComponent;

    public map: any;
    public key = "R6YBZ-BS6CF-N3QJB-NXEWE-AILU3-3GF6F"
    public ll = {
        lat: 28.663479,
        lng: 115.814137
    }

    public status = '';
    public markers = []
    public InfoWindow = [];

    public typelist = [
        {
            name: "公交",
            icon: "./assets/images/HouseDetails/icon_bus.png"
        },
        {
            name: "学校",
            icon: "./assets/images/HouseDetails/icon_school.png"
        },
        {
            name: "餐饮",
            icon: "./assets/images/HouseDetails/icon_restaurant.png"
        },
        {
            name: "购物",
            icon: "./assets/images/HouseDetails/icon_shopping.png"
        },
        {
            name: "医院",
            icon: "./assets/images/HouseDetails/icon_hospital.png"
        },
    ]

    public isMini = false;

    constructor(private zone: NgZone) { }

    ngOnInit(option) { }

    onReady(mapNative: any) {

        console.log(this.options);


        this.isMini = this.options.type === 'mini' ? true : false;

        if (this.options.latng) {
            this.ll = this.options.latng;
        }

        let qll = new qq.maps.LatLng(this.ll.lat, this.ll.lng);

        mapNative.setOptions({
            zoom: 12,
            center: qll,
            zoomControl: false,
            draggable: !this.isMini,
            mapTypeControl: false,
            scaleControl: true,
            scaleControlOptions: {
                position: qq.maps.ControlPosition.LEFT_TOP
            }
        });
        this.map = mapNative;
        this.status = '加载完成';

        this.createMaker({ "latLng": qll, "name": this.options.name }, true);

        // 添加监听事件
        qq.maps.event.addListener(this.map, 'click', (event: any) => {

            this.zone.run(() => {

                this.status = `click ${+new Date()}`;

                if (this.isMini) {
                    console.log("mini 版");

                    this.redirect.emit("");
                }

            });
        });

        console.log(this.options.key);


        if (this.options.key) {
            this.search(this.options.key);
        }

        this.createInforWin({ title: this.options.name }, { lat: this.ll.lat, lng: this.ll.lng })

    }

    search(str) {


        if (!this.isMini) {

            //清除覆盖物
            this.deleteOverlays(this.InfoWindow);
            this.deleteOverlays(this.markers);

            //楼盘坐标
            this.createMaker({ "latLng": new qq.maps.LatLng(this.ll.lat, this.ll.lng), name: this.options.name }, true);


            //检索
            let latlngBounds = new qq.maps.LatLngBounds();
            let searchService = new qq.maps.SearchService({
                pageIndex: 0,
                pageCapacity: 25,
                autoExtend: false,
                complete: results => {

                    var pois = results.detail.pois;

                    for (var i = 0, l = pois.length; i < l; i++) {
                        var poi = pois[i];
                        //扩展边界范围，用来包含搜索到的Poi点
                        latlngBounds.extend(poi.latLng);
                        this.createMaker(poi);
                    }
                    //调整地图视野
                    this.map.fitBounds(latlngBounds);

                },
                //若服务请求失败，则运行以下函数
                error: function () {
                    alert("出错了。");
                }
            });

            var SearchCenterLatlng = new qq.maps.LatLng(this.ll.lat, this.ll.lng);
            searchService.searchNearBy(str, SearchCenterLatlng, 5000);

        } else {
            this.redirect.emit(str);
        }


    }

    createMaker(poi, isHousePoi?) {
        let icon = "";
        if (isHousePoi) {
            icon = "./assets/images/HouseDetails/icon_map_location.png"
        } else {
            icon = "./assets/images/HouseDetails/icon_map.png"
        }

        var marker = new qq.maps.Marker({
            map: this.map,
            position: poi.latLng
        });

        var anchor = new qq.maps.Point(10, 30),
            size = new qq.maps.Size(42, 68),
            origin = new qq.maps.Point(0, 0),
            markerIcon = new qq.maps.MarkerImage(
                icon,
                size,
                origin,
                anchor
            );
        marker.setIcon(markerIcon);
        marker.setTitle(poi.name);

        //覆盖物事件
        this.markerClick(marker)
        //添加标注数组
        this.markers.push(marker);
    }

    markerClick(marker) {
        //获取标记的点击事件
        qq.maps.event.addListener(marker, 'click', event => {
            this.createInforWin(marker, event.latLng);
        });
    }

    createInforWin(marker, event) {
        this.deleteOverlays(this.InfoWindow);
        //添加到提示窗
        var info = new qq.maps.InfoWindow({
            map: this.map
        });
        info.open();
        info.setContent('<div style="text-align:center;white-space:nowrap;' +
            'margin:10px;">' + marker.title + '</div>');

        let ll = new qq.maps.LatLng(event.lat, event.lng);
        info.setPosition(ll);
        this.InfoWindow.push(info);
    }


    deleteOverlays(markersArray) {

        if (markersArray) {
            for (let i in markersArray) {
                markersArray[i].setMap(null);
            }
            markersArray.length = 0;
        }
    }

    ngOnDestroy(): void {
        ['click'].forEach(eventName => {
            qq.maps.event.clearListeners(this.map, eventName);
        });
    }
}
